import os

import pydicom

#SliceThickness X SpacingBetweenSlices

base_dir = '/media/imed/d9f520b2-6e7a-4842-af77-fba3ad2d8d27/test_to'

for folder in os.listdir(base_dir):
    folder_path = os.path.join(base_dir, folder)
    for dcmfile in os.listdir(folder_path):
        dcm_path = os.path.join(folder_path, dcmfile)
        ds = pydicom.dcmread(dcm_path, stop_before_pixels=True)
        if hasattr(ds, 'SliceThickness') and not hasattr(ds, 'SpacingBetweenSlices'):
            s1 = ds.SliceThickness
            new_folder_name = folder + f'_{s1}x'
            new_path = os.path.join(base_dir, new_folder_name)
            os.rename(folder_path, new_path)
            break

        elif not hasattr(ds, 'SliceThickness') and hasattr(ds, 'SpacingBetweenSlices'):
            s2 = ds.SpacingBetweenSlices
            new_folder_name = folder + f'_x{s2}'
            new_path = os.path.join(base_dir, new_folder_name)
            os.rename(folder_path, new_path)
            break

        elif hasattr(ds, 'SliceThickness') and hasattr(ds, 'SpacingBetweenSlices'):
            s1 = ds.SliceThickness
            s2 = ds.SpacingBetweenSlices
            new_folder_name = folder + f'_{s1}x{s2}'
            new_path = os.path.join(base_dir, new_folder_name)
            os.rename(folder_path, new_path)
            break

        else:
            print(folder)
            break

